<template>
  <a class="bvideo" href="https://space.bilibili.com/432028432"
    >可视化场景分享</a
  >
  <a class="view" id="view" href="#">默认视图</a>
  <div
    style="
      position: fixed;
      width: 100px;
      height: 30px;
      z-index: 9;
      margin-left: 180px;
    "
  >
    <button v-if="yanmoshow" id="huizhi" @click="huizhiyanmo">
      绘制淹没分析
    </button>
    <button @click="clearAllEntities">清除淹没分析</button>
  </div>
  <div v-if="buttonshow">
    <button
      @click="xiasnow('雪')"
      style="position: fixed; z-index: 9; margin-left: 300px"
    >
      下雪
    </button>
    <button
      @click="xiasnow('雨')"
      style="position: fixed; z-index: 9; margin-left: 360px"
    >
      下雨
    </button>
    <button
      @click="xiasnow('雾')"
      style="position: fixed; z-index: 9; margin-left: 420px"
    >
      下雾
    </button>
    <button
      @click="xiasnow('测量')"
      style="position: fixed; z-index: 9; margin-left: 480px"
    >
      测量
    </button>
    <button
      @click="xiasnow('绘制')"
      style="position: fixed; z-index: 9; margin-left: 540px"
    >
      绘制
    </button>
    <button
      @click="xiasnow('返回')"
      style="position: fixed; z-index: 9; margin-left: 600px"
    >
      返回
    </button>
  </div>
  <div id="sceneContainer"></div>
  <div id="loadingIndicator" class="loadingIndicator"></div>
  <div id="loadingIndicator2" class="loadingIndicator2"></div>
  <router-view></router-view>
  <div class="tankuang" v-if="centerDialogVisible">
    <div class="close" @click="centerDialogVisible = false"></div>
    <div>{{ name }}</div>
    <div class="height">高度：{{ height }}</div>
    <div class="height2">占地面积：{{ area }}</div>
  </div>
  <!-- <el-dialog
    v-model="centerDialogVisible"
    title="模型弹出框"
    width="500"
    align-center
  >
    <span>{{ msg }}</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="centerDialogVisible = false">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog> -->
  <!-- <Snow v-if="false" />
  <Rain v-if="false" /> -->
</template>

<script setup>
import * as turf from "@turf/turf";
import { ref, reactive, onMounted } from "vue";
import Snow from "@/views/particle/snow.vue";
import Rain from "@/views/particle/rain.vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
let yanmoshow = ref(true);
let buttonshow = ref(true);
let name = ref("");
let height = ref("");
let area = ref("");
let centerDialogVisible = ref(false);
let msg = ref("");
const router = useRouter();
const store = useStore();
let data = reactive({
  polylinedata: null,
});
// import waterPrimitive from "./WaterPrimitive1";
/**
 * m3d源码场景 请勿下载后售卖
 * gitee:https://gitee.com/m3d
 * b站:https://www.bilibili.com/video/BV1yG4y1m7dF/
 */
Cesium.Ion.defaultAccessToken =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJjMzU2ZTQyYy1iOTU5LTQ5MDQtOGNkNC0yYzcxMTI1ZDJiZGQiLCJpZCI6NzY1OTcsImlhdCI6MTYzOTU2MDcwOH0.kbWigipGD6l2OPBGpnkkN6dzp8NuNjoHNNM1NF4gaIo";
let viewer;
let imagerLayer;
let building;
let model0;
let model1;
let model2;
let model3;
let waterPrimitive1;

let activeShapePoints = [];
let floatingPoint = undefined;
let activeShape = undefined;
let handler = undefined;
let isDraw = false;
let maxWaterHeight = 2000;
let minWaterHeight = 0;
let waterHeight = 0;
// let waterPrimitive = undefined;
let tempEntities = [];
let undefinedisDraw = "";
/**
 * 自定义材质线 github:cesium-materialLine
 * @param {*} options
 * @returns
 */
function CustomMaterialLine(options) {
  let Color = Cesium.Color,
    defaultValue = Cesium.defaultValue,
    defined = Cesium.defined,
    defineProperties = Object.defineProperties,
    Event = Cesium.Event,
    createPropertyDescriptor = Cesium.createPropertyDescriptor,
    Property = Cesium.Property,
    Material = Cesium.Material,
    defaultColor = Color.WHITE,
    currentTime = window.performance.now(),
    MaterialType =
      options.MaterialType || "wallType" + parseInt(Math.random() * 1000);
  function PolylineCustomMaterialProperty(options) {
    options = defaultValue(options, defaultValue.EMPTY_OBJECT);
    this._definitionChanged = new Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this.color = options.color || Cesium.Color.BLUE;
    this.duration = options.duration || 1000;
    this._time = currentTime;
  }
  defineProperties(PolylineCustomMaterialProperty.prototype, {
    isvarant: {
      get: function () {
        return false;
      },
    },
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      },
    },
    color: createPropertyDescriptor("color"),
  });
  PolylineCustomMaterialProperty.prototype.getType = function (time) {
    return MaterialType;
  };
  PolylineCustomMaterialProperty.prototype.getValue = function (time, result) {
    if (!defined(result)) {
      result = {};
    }
    window.m3d = true;
    result.color = Property.getValueOrClonedDefault(
      this._color,
      time,
      defaultColor,
      result.color
    );
    result.image = options.image;
    result.time =
      ((window.performance.now() - this._time) % this.duration) / this.duration;
    return result;
  };
  PolylineCustomMaterialProperty.prototype.equals = function (other) {
    return (
      this === other ||
      (other instanceof PolylineCustomMaterialProperty &&
        Property.equals(this._color, other._color))
    );
  };
  Material._materialCache.addMaterial(MaterialType, {
    fabric: {
      type: MaterialType,
      uniforms: {
        color: options.color || new Cesium.Color(1.0, 0.0, 0.0, 0.5),
        image: options.image,
        time: 0,
      },
      source: `czm_material czm_getMaterial(czm_materialInput materialInput)
                {
                    czm_material material = czm_getDefaultMaterial(materialInput);
                    vec2 st = materialInput.st;
                    if(texture(image, vec2(0.0, 0.0)).a == 1.0){
                        discard;
                    }else{
                        material.alpha = texture(image, vec2(1.0 - fract(time - st.s), st.t)).a * color.a;
                    }
                    material.diffuse = max(color.rgb * material.alpha * 3.0, color.rgb);
                    return material;
                }
                `,
    },
    translucent: function (material) {
      return true;
    },
  });
  return new PolylineCustomMaterialProperty(options);
}

/**
 * 初始化viewer
 */
const initViewer = () => {
  viewer = new Cesium.Viewer("sceneContainer", {
    infoBox: false,
    shouldAnimate: false,
    vrButton: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    baseLayerPicker: false,
    navigationHelpButton: false,
    animation: false,
    timeline: true,
    fullscreenButton: false,
    terrainProvider: Cesium.createWorldTerrain({
      requestWaterMask: true,
      requestVertexNormals: true,
    }),
    contextOptions: {
      requestWebgl1: false,
      allowTextureFilterAnisotropic: true,
      webgl: {
        alpha: false,
        depth: true,
        stencil: false,
        antialias: true,
        powerPreference: "high-performance",
        premultipliedAlpha: true,
        preserveDrawingBuffer: false,
        failIfMajorPerformanceCaveat: false,
      },
    },
  });
  store.commit("initViewer", viewer);
  window.viewer = viewer;
  viewer._cesiumWidget._creditContainer.style.display = "none";
  viewer.resolutionScale = 1.2;
  viewer.scene.msaaSamples = 4;
  viewer.postProcessStages.fxaa.enabled = true;
  viewer.scene.globe.depthTestAgainstTerrain = true;
  viewer.scene.debugShowFramesPerSecond = true;
  viewer.scene.globe.shadows = Cesium.ShadowMode.ENABLED;

  viewer.shadows = true;
  viewer.shadowMap.size = 2048;
  viewer.shadowMap.softShadows = false;
  viewer.shadowMap.maximumDistance = 4000;

  viewer.scene.globe.enableLighting = true;
  viewer.scene.fog.minimumBrightness = 0.5;
  viewer.scene.fog.density = 2.0e-4 * 1.2;
  viewer.scene.globe.atmosphereLightIntensity = 20;
  viewer.scene.globe.atmosphereBrightnessShift = -0.01;

  imagerLayer = viewer.imageryLayers.get(0);

  viewer.scene.postProcessStages.bloom.enabled = false;
  viewer.scene.postProcessStages.bloom.uniforms.contrast = 119;
  viewer.scene.postProcessStages.bloom.uniforms.brightness = -0.4;
  viewer.scene.postProcessStages.bloom.uniforms.glowOnly = false;
  viewer.scene.postProcessStages.bloom.uniforms.delta = 0.9;
  viewer.scene.postProcessStages.bloom.uniforms.sigma = 3.78;
  viewer.scene.postProcessStages.bloom.uniforms.stepSize = 5;
  viewer.scene.postProcessStages.bloom.uniforms.isSelected = false;

  viewer.scene.postProcessStages.ambientOcclusion.enabled = false;
  viewer.scene.postProcessStages.ambientOcclusion.uniforms.intensity = 1.5;
  viewer.scene.postProcessStages.ambientOcclusion.uniforms.bias = 0.4;
  viewer.scene.postProcessStages.ambientOcclusion.uniforms.lengthCap = 0.45;
  viewer.scene.postProcessStages.ambientOcclusion.uniforms.stepSize = 1.8;
  viewer.scene.postProcessStages.ambientOcclusion.uniforms.blurStepSize = 1.0;

  // viewer.scene.screenSpaceCameraController.minimumZoomDistance = 0;
  // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 30000;

  viewer.canvas.addEventListener("click", function () {
    const camera = viewer.scene.camera;
    const position = camera.position;
    const heading = camera.heading;
    const pitch = camera.pitch;
    const roll = camera.roll;
    let xyzCoordinates = [position.x, position.y, position.z];

    // 将XYZ坐标转换为Cesium的Cartesian3对象
    let cartesian3 = Cesium.Cartesian3.fromArray(xyzCoordinates);

    // 将Cartesian3坐标转换为经纬度坐标
    let cartographic =
      Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian3);

    // 获取经度、纬度和高程
    let longitude = Cesium.Math.toDegrees(cartographic.longitude);
    let latitude = Cesium.Math.toDegrees(cartographic.latitude);
    let height = cartographic.height;

    console.log(`经度: ${longitude}, 纬度: ${latitude}, 高程: ${height}`);
    // console.log(position)
    console.log(`Heading: ${heading}`);
    console.log(`Pitch: ${pitch}`);
    console.log(`Roll: ${roll}`);
  });
};

/**
 * 初始化场景
 */
const initScene = () => {
  const initTiles = () => {
    building = viewer.scene.primitives.add(
      Cesium.createOsmBuildings({
        customShader: new Cesium.CustomShader({
          uniforms: {
            u_envTexture: {
              value: new Cesium.TextureUniform({
                url: "/Static/images/sky.jpg",
              }),
              type: Cesium.UniformType.SAMPLER_2D,
            },
            u_envTexture2: {
              value: new Cesium.TextureUniform({
                url: "/Static/images/pic.jpg",
              }),
              type: Cesium.UniformType.SAMPLER_2D,
            },
            u_isDark: {
              value: false,
              type: Cesium.UniformType.BOOL,
            },
          },
          mode: Cesium.CustomShaderMode.REPLACE_MATERIAL,
          lightingModel: Cesium.LightingModel.UNLIT,
          fragmentShaderText: `
                            void fragmentMain(FragmentInput fsInput,inout czm_modelMaterial material) {
                                vec3 positionMC = fsInput.attributes.positionMC;
                                vec3 positionEC = fsInput.attributes.positionEC;
                                vec3 normalEC = fsInput.attributes.normalEC;
                                vec3 posToCamera = normalize(-positionEC); 
                                vec3 coord = normalize(vec3(czm_inverseViewRotation * reflect(posToCamera, normalEC)));
                                float ambientCoefficient = 0.3;
                                float diffuseCoefficient = max(0.0, dot(normalEC, czm_sunDirectionEC) * 1.0);
                                if(u_isDark){

                                    // dark
                                    vec4 darkRefColor = texture(u_envTexture2, vec2(coord.x, (coord.z - coord.y) / 2.0));
                                    material.diffuse = mix(mix(vec3(0.3), vec3(0.1,0.2,0.4),clamp(positionMC.z / 200., 0.0, 1.0)) , darkRefColor.rgb ,0.3);
                                    material.diffuse *= 0.2;
                                    // 注意shader中写浮点数是 一定要带小数点 否则会报错 比如0需要写成0.0 1要写成1.0
                                    float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
                                    float _heightRange = 20.0; // 高亮的范围(_baseHeight ~ _baseHeight + _heightRange)
                                    float _glowRange = 300.0; // 光环的移动范围(高度)
                                    // 建筑基础色
                                    float czm_height = positionMC.z - _baseHeight;
                                    float czm_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
                                    float czm_a12 = czm_height / _heightRange + sin(czm_a11) * 0.1;
        
                                    float times = czm_frameNumber / 60.0;
                                    material.diffuse *= vec3(czm_a12);// 渐变
                                    // 动态光环
                                    float time = fract(czm_frameNumber / 360.0);
                                    time = abs(time - 0.5) * 2.0;
                                    float czm_h = clamp(czm_height / _glowRange, 0.0, 1.0);
                                    float czm_diff = step(0.005, abs(czm_h - time));
                                    material.diffuse += material.diffuse * (1.0 - czm_diff);
                                } else {

                                    // day
                                    vec4 dayRefColor = texture(u_envTexture, vec2(coord.x, (coord.z - coord.y) / 3.0));
                                    material.diffuse = mix(mix(vec3(0.000), vec3(0.5),clamp(positionMC.z / 300., 0.0, 1.0)) , dayRefColor.rgb ,0.3);
                                    material.diffuse *= min(diffuseCoefficient + ambientCoefficient, 1.0);
                                }
                                material.alpha = 1.0;
                            }
                             `,
        }),
      })
    );
    model0 = viewer.scene.primitives.add(
      new Cesium.Model.fromGltf({
        url: "/Static/data/shanghai_tower/scene.gltf",
        id: 1010,
        imageBasedLighting: imageBasedLighting,
        customShader: new Cesium.CustomShader({
          uniforms: {
            u_texture: {
              value: new Cesium.TextureUniform({
                url: "/Static/images/color.png",
              }),
              type: Cesium.UniformType.SAMPLER_2D,
            },
            u_isDark: {
              value: true,
              type: Cesium.UniformType.BOOL,
            },
          },
          lightingModel: Cesium.LightingModel.PBR,
          fragmentShaderText: `
                            void fragmentMain(FragmentInput fsInput,inout czm_modelMaterial material) {
                                if(u_isDark){
                                    vec2 texCoord = fsInput.attributes.texCoord_0 * 0.3;
                                    float times = czm_frameNumber / 120.0;
                                    vec4 textureColor = texture(u_texture,vec2(fract(texCoord.s),float(texCoord.t) - times));
                                    material.diffuse += textureColor.rgb * 0.8;
                                }
                            }
                             `,
        }),
        modelMatrix: generateModelMatrix(
          [121.49805570610201, 31.23266477688614, 400],
          [0, 0, 45],
          [3, 3, 2.5]
        ),
      })
    );

    model1 = viewer.scene.primitives.add(
      Cesium.Model.fromGltf({
        id: 1011,
        url: "/Static/data/building_-_beveled_corners_-_shiny/scene.gltf",
        imageBasedLighting: imageBasedLighting,
        customShader: new Cesium.CustomShader({
          uniforms: {
            u_texture: {
              value: new Cesium.TextureUniform({
                url: "/Static/images/pic.jpg",
              }),
              type: Cesium.UniformType.SAMPLER_2D,
            },
            u_isDark: {
              value: true,
              type: Cesium.UniformType.BOOL,
            },
          },
          lightingModel: Cesium.LightingModel.PBR,
          fragmentShaderText: `
                            void fragmentMain(FragmentInput fsInput,inout czm_modelMaterial material) {
                                if(u_isDark){
                                    vec2 texCoord = fsInput.attributes.texCoord_0 * 0.3;
                                    float times = czm_frameNumber / 120.0;
                                    vec4 textureColor = texture(u_texture,vec2(fract(texCoord.s),float(texCoord.t) - times));
                                    material.diffuse += textureColor.rgb * 1.5;
                                }
                            }
                             `,
        }),
        modelMatrix: generateModelMatrix(
          [121.50306517515779, 31.236594411927722, 0],
          [0, 0, 0],
          [3, 3, 4.4]
        ),
      })
    );

    model2 = viewer.scene.primitives.add(
      Cesium.Model.fromGltf({
        id: 1022,
        url: "/Static/data/building_-_octagonal_-_shiny/scene.gltf",
        imageBasedLighting: imageBasedLighting,
        customShader: new Cesium.CustomShader({
          uniforms: {
            u_texture: {
              value: new Cesium.TextureUniform({
                url: "/Static/images/color2.png",
              }),
              type: Cesium.UniformType.SAMPLER_2D,
            },
            u_isDark: {
              value: true,
              type: Cesium.UniformType.BOOL,
            },
          },
          lightingModel: Cesium.LightingModel.PBR,
          fragmentShaderText: `
                            void fragmentMain(FragmentInput fsInput,inout czm_modelMaterial material) {
                                if(u_isDark){
                                    vec2 texCoord = fsInput.attributes.texCoord_0 * 0.5;
                                    float times = czm_frameNumber / 120.0;
                                    vec4 textureColor = texture(u_texture,vec2(float(texCoord.s) - times),fract(texCoord.t));
                                    material.diffuse += textureColor.rgb * 1.5;
                                }
                            }
                             `,
        }),
        modelMatrix: generateModelMatrix(
          [121.50140479453857, 31.237266571858395, 0],
          [0, 0, 0],
          [2.5, 2.5, 3.0]
        ),
      })
    );

    model3 = viewer.scene.primitives.add(
      Cesium.Model.fromGltf({
        id: 1023,
        url: "/Static/data/oriental_pearl_shanghai. (1)/scene.gltf",
        imageBasedLighting: imageBasedLighting,
        customShader: new Cesium.CustomShader({
          uniforms: {
            u_texture: {
              value: new Cesium.TextureUniform({
                url: "/Static/images/color.png",
              }),
              type: Cesium.UniformType.SAMPLER_2D,
            },
            u_isDark: {
              value: true,
              type: Cesium.UniformType.BOOL,
            },
          },
          lightingModel: Cesium.LightingModel.PBR,
          fragmentShaderText: `
                            void fragmentMain(FragmentInput fsInput,inout czm_modelMaterial material) {
                                if(u_isDark){
                                    vec2 texCoord = fsInput.attributes.texCoord_0 * 0.5;
                                    float times = czm_frameNumber / 30.0;
                                    vec4 textureColor = texture(u_texture,vec2(fract(texCoord.s),float(texCoord.t) - times));
                                    material.diffuse += textureColor.rgb * 0.8;
                                }  
                            }
                             `,
        }),
        modelMatrix: generateModelMatrix(
          [121.49697607088487, 31.241891679352257, 10],
          [0, 0, 0],
          [0.15, 0.15, 0.126]
        ),
      })
    );

    viewer.screenSpaceEventHandler.setInputAction(function (movement) {
      const pickedObject = viewer.scene.pick(movement.position); // 检测点击的对象
      if (Cesium.defined(pickedObject)) {
        const model = pickedObject.primitive;
        console.log(model);
        if (model.id == 1010) {
          centerDialogVisible.value = true;
          msg.value = "您点击了黑色最高楼，此楼楼高522m，占地面积50平方公里";
          name.value = "黑色一楼";
          height.value = "510m";
          area.value = "20万平方米";
          // alert("您点击了黑色最高楼");
        } else if (model.id == 1023) {
          centerDialogVisible.value = true;
          msg.value = "您点击了东方明珠，此楼楼高592m,占地面积30平方公里";
          name.value = "东方明珠";
          height.value = "468m";
          area.value = "10万平方米";
          // alert("您点击了东方明珠");
        } else if (model.id == 1022) {
          centerDialogVisible.value = true;
          msg.value = "您点击了黑色第三栋楼，此楼楼高412m,占地面积20平方公里";
          name.value = "黑色三楼";
          height.value = "420m";
          area.value = "5万平方米";
          // alert("您点击了东方明珠");
        } else if (model.id == 1011) {
          centerDialogVisible.value = true;
          msg.value = "您点击了黑色第二栋楼，此楼楼高497m,占地面积30平方公里";
          name.value = "黑色二楼";
          height.value = "470m";
          area.value = "21万平方米";
          // alert("您点击了东方明珠");
        }
        // alert('你点击了模型！');
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  };

  const initWater = async () => {
    const waterPlane = [];
    const waterData = await Cesium.Resource.fetchJson({
      url: "/Static/data/water.json",
    });
    waterData.features.map((feature) => {
      feature.geometry.coordinates[0].map((coordinate) => {
        waterPlane.push(Cesium.Cartesian3.fromDegrees(...coordinate));
      });
    });
    const polygon = new Cesium.PolygonGeometry({
      polygonHierarchy: new Cesium.PolygonHierarchy(waterPlane),
    });
    const instance = new Cesium.GeometryInstance({
      geometry: polygon,
    });
    waterPrimitive1 = new Cesium.GroundPrimitive({
      geometryInstances: instance,
      appearance: new Cesium.MaterialAppearance({
        material: new Cesium.Material({
          fabric: {
            type: Cesium.Material.WaterType,
            uniforms: {
              baseWaterColor: Cesium.Color.fromCssColorString("#62809b"),
              blendColor: new Cesium.Color(0, 1, 0.699, 1),
              // specularMap: Material.DefaultImageId,
              normalMap:
                "https://cesium.com/downloads/cesiumjs/releases/1.103/Build/Cesium/Assets/Textures/waterNormals.jpg",
              frequency: 1000,
              animationSpeed: 0.01,
              amplitude: 2,
              specularIntensity: 1,
              fadeFactor: 3,
            },
          },
        }),
        translucent: false,
      }),
      asynchronous: false,
    });
    viewer.scene.primitives.add(waterPrimitive1);

    // 创建材质线
    let getCustomMaterialLine = (image, color) => {
      return new CustomMaterialLine({
        image: image,
        color: color,
        duration: 1000,
      });
    };
    const createRoad = (url) => {
      let promise = Cesium.GeoJsonDataSource.load(url);
      promise.then((dataSource) => {
        viewer.dataSources.add(dataSource);
        let entities = dataSource.entities.values;
        for (let o = 0; o < entities.length; o++) {
          entities[o].polyline.width = 3;
          entities[o].polyline.clampToGround = true;
          entities[o].polyline.material = getCustomMaterialLine(
            "/Static/images/line.png",
            Cesium.Color.fromRandom()
          );
        }
      });
    };

    createRoad("/Static/data/road.json");
    createRoad("/Static/data/road2.json");
  };

  initTiles();

  initWater();
};

/**
 * 初始化场景事件
 */
const initEvent = () => {
  let _sn = 0;
  const updateScene = () => {
    const sd = Cesium.Cartesian3.normalize(
      viewer.scene.sun._boundingVolume.center,
      new Cesium.Cartesian3()
    );
    const vd = Cesium.Cartesian3.normalize(
      viewer.camera.position,
      new Cesium.Cartesian3()
    );
    const sn = parseFloat(Cesium.Cartesian3.dot(vd, sd).toFixed(3));
    if (sn === _sn) return false;
    viewer.postProcessStages.bloom.enabled = false;
    viewer.scene.postProcessStages.ambientOcclusion.enabled = true;
    building.customShader.uniforms.u_isDark.value = false;
    model0.customShader.uniforms.u_isDark.value = false;
    model1.customShader.uniforms.u_isDark.value = false;
    model2.customShader.uniforms.u_isDark.value = false;
    model3.customShader.uniforms.u_isDark.value = false;
    const value = Cesium.Math.clamp(sn, 0, 1);
    if (imagerLayer) imagerLayer.brightness = value + 0.3;
    if (waterPrimitive1)
      waterPrimitive1.appearance.material.uniforms.baseWaterColor =
        Cesium.Color.multiplyByScalar(
          Cesium.Color.fromCssColorString("#62809b"),
          value + 0.3,
          new Cesium.Color()
        );
    if (sn < 0) {
      viewer.postProcessStages.bloom.enabled = true;
      viewer.scene.postProcessStages.ambientOcclusion.enabled = false;
      building.customShader.uniforms.u_isDark.value = true;
      model0.customShader.uniforms.u_isDark.value = true;
      model1.customShader.uniforms.u_isDark.value = true;
      model2.customShader.uniforms.u_isDark.value = true;
      model3.customShader.uniforms.u_isDark.value = true;
    }
    if (sn < -0.1 && waterPrimitive1) {
      let scale = parseFloat(
        Cesium.Math.clamp((sn - -0.8) / (-0.1 - -0.8), 1.0, 1.5)
      );
      waterPrimitive1.appearance.material.uniforms.baseWaterColor =
        Cesium.Color.multiplyByScalar(
          Cesium.Color.fromCssColorString("#62809b"),
          scale,
          new Cesium.Color()
        );
    }
    _sn = sn;
  };
  viewer.scene.postRender.addEventListener(() => updateScene());
  const onGlobeEvent =
    viewer.scene.globe.tileLoadProgressEvent.addEventListener((tileNum) => {
      if (tileNum > 2) {
        closeLoading(), showUI(), onGlobeEvent();
      }
    });

  document.getElementById("view").onclick = function () {
    viewer.camera.setView({
      destination: {
        x: -2852928.497690295,
        y: 4652428.954517055,
        z: 3291891.0380489714,
      },
      orientation: {
        heading: Cesium.Math.toRadians(212.20287149232163),
        pitch: Cesium.Math.toRadians(-11.215466997379062),
        roll: Cesium.Math.toRadians(0.004033823235683256),
      },
    });
  };
  viewer.camera.setView({
    destination: {
      x: -2850554.9246458095,
      y: 4656672.153306185,
      z: 3287574.727124352,
    },
    orientation: {
      heading: Cesium.Math.toRadians(48.72529042457395),
      pitch: Cesium.Math.toRadians(-10.899276751527792),
      roll: Cesium.Math.toRadians(0.0014027234956804583),
    },
  });

  viewer.clock.currentTime = Cesium.JulianDate.fromIso8601(
    "2023-01-01T06:00:00Z"
  );
};

const initGUI = () => {};
const L00 = new Cesium.Cartesian3(
  1.234709620475769,
  1.221461296081543,
  1.273156881332397
);
const L1_1 = new Cesium.Cartesian3(
  1.135921120643616,
  1.171217799186707,
  1.287644743919373
);
const L10 = new Cesium.Cartesian3(
  1.245193719863892,
  1.245591878890991,
  1.282818794250488
);
const L11 = new Cesium.Cartesian3(
  -1.106930732727051,
  -1.112522482872009,
  -1.153198838233948
);
const L2_2 = new Cesium.Cartesian3(
  -1.086226940155029,
  -1.079731941223145,
  -1.101912498474121
);
const L2_1 = new Cesium.Cartesian3(
  1.189834713935852,
  1.185906887054443,
  1.214385271072388
);
const L20 = new Cesium.Cartesian3(
  0.01778045296669,
  0.02013735473156,
  0.025313569232821
);
const L21 = new Cesium.Cartesian3(
  -1.086826920509338,
  -1.084611177444458,
  -1.111204028129578
);
const L22 = new Cesium.Cartesian3(
  -0.05241484940052,
  -0.048303380608559,
  -0.041960217058659
);
const coefficients = [L00, L1_1, L10, L11, L2_2, L2_1, L20, L21, L22];
let imageBasedLighting = new Cesium.ImageBasedLighting({
  specularEnvironmentMaps: "./Static/images/kiara_6_afternoon_2k_ibl.ktx2",
  sphericalHarmonicCoefficients: coefficients,
});

/**
 * 生成矩阵
 * @param {*} position
 * @param {*} rotation
 * @param {*} scale
 * @returns
 */
const generateModelMatrix = (
  position = [0, 0, 0],
  rotation = [0, 0, 0],
  scale = [1, 1, 1]
) => {
  const rotationX = Cesium.Matrix4.fromRotationTranslation(
    Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(rotation[0]))
  );

  const rotationY = Cesium.Matrix4.fromRotationTranslation(
    Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(rotation[1]))
  );

  const rotationZ = Cesium.Matrix4.fromRotationTranslation(
    Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(rotation[2]))
  );
  if (!(position instanceof Cesium.Cartesian3)) {
    position = Cesium.Cartesian3.fromDegrees(...position);
  }
  const enuMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
  Cesium.Matrix4.multiply(enuMatrix, rotationX, enuMatrix);
  Cesium.Matrix4.multiply(enuMatrix, rotationY, enuMatrix);
  Cesium.Matrix4.multiply(enuMatrix, rotationZ, enuMatrix);
  const scaleMatrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(...scale));
  const modelMatrix = Cesium.Matrix4.multiply(
    enuMatrix,
    scaleMatrix,
    new Cesium.Matrix4()
  );

  return modelMatrix;
};

const main = () => {
  initViewer();
  initScene();
  initEvent();
  initGUI();
};

// new window.WOW().init();
function showUI() {
  $("body").append(`
    <div id="uiContainer">
        <div id="topUI" class="wow bounceInDown" data-wow-duration="1.2s"></div>
        <div id="leftUI" class="wow bounceInLeft" data-wow-duration="1.2s"></div>
        <div id="roghtUI" class="wow bounceInRight" data-wow-duration="1.2s"></div>
    </div>`);
}
function closeLoading() {
  $("#loadingIndicator").hide();
  $("#loadingIndicator2").hide();
}

function showLoading() {
  $("#loadingIndicator").show();
  $("#loadingIndicator2").show();
}

onMounted(() => {
  main();
});
const huizhiyanmo = () => {
  yanmoshow.value = false;
  buttonshow.value = false;
  router.push("/");
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(
      119.9881430682179,
      30.674708206014962,
      1267.571673121449
    ), // 纬度、经度和高度
    orientation: {
      heading: 0.3360406546942265,
      pitch: -0.43583580983291315,
      roll: 6.283149698014369,
    },
  });
  activeShapePoints = [];
  floatingPoint = undefined;
  activeShape = undefined;
  handler = undefinedisDraw = false;
  maxWaterHeight = 5000;
  minWaterHeight = 0;
  waterHeight = 0;
  // waterPrimitive = undefined;
  tempEntities = [];
  // 开启深度检测
  viewer.scene.globe.depthTestAgainstTerrain = true;
  handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  handler.setInputAction((event) => {
    const earthPosition = viewer.scene.pickPosition(event.position);
    if (Cesium.defined(earthPosition)) {
      if (activeShapePoints.length === 0) {
        floatingPoint = createPoint(earthPosition);
        activeShapePoints.push(earthPosition);
        const dynamicPositions = new Cesium.CallbackProperty(function () {
          return new Cesium.PolygonHierarchy(activeShapePoints);
        }, false);
        activeShape = drawShape(
          dynamicPositions,
          Cesium.Color.fromBytes(64, 157, 253, 50)
        );
      }
      activeShapePoints.push(earthPosition);
      tempEntities.push(createPoint(earthPosition));
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  handler.setInputAction((event) => {
    if (Cesium.defined(floatingPoint)) {
      const newPosition = viewer.scene.pickPosition(event.endPosition);
      if (Cesium.defined(newPosition)) {
        floatingPoint.position.setValue(newPosition);
        activeShapePoints.pop();
        activeShapePoints.push(newPosition);
      }
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  handler.setInputAction((event) => {
    activeShapePoints.pop();
    if (activeShapePoints.length < 3) return;
    tempEntities.push(drawPolyline(activeShapePoints));
    let ploy = drawShape(
      activeShapePoints,
      Cesium.Color.fromBytes(64, 157, 253, 20)
    );
    tempEntities.push(ploy);
    window.viewer.entities.remove(floatingPoint);
    window.viewer.entities.remove(activeShape);
    floatingPoint = undefined;
    activeShape = undefined;
    handler.destroy(); // 关闭事件句柄
    handler = null;
    induationAnalysis();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

const getAreaHeight = async (positions) => {
  let startP = positions[0];
  let endP = positions[positions.length - 1];
  if (startP.x != endP.x && startP.y != endP.y && startP.z != endP.z)
    positions.push(positions[0]);

  const tempPoints = [];
  for (let i = 0; i < positions.length; i++) {
    var ellipsoid = window.viewer.scene.globe.ellipsoid;
    var cartographic = ellipsoid.cartesianToCartographic(positions[i]);
    var lat = Cesium.Math.toDegrees(cartographic.latitude);
    var lng = Cesium.Math.toDegrees(cartographic.longitude);
    tempPoints.push([lng, lat]);
  }
  var line = turf.lineString(tempPoints);
  var chunk = turf.lineChunk(line, 10, {
    units: "meters",
  });

  const tempArray = [];
  chunk.features.forEach((f) => {
    f.geometry.coordinates.forEach((c) => {
      tempArray.push(Cesium.Cartographic.fromDegrees(c[0], c[1]));
    });
  });

  var promise = Cesium.sampleTerrainMostDetailed(
    window.viewer.terrainProvider,
    tempArray
  );
  const updatedPositions = await Cesium.sampleTerrainMostDetailed(
    window.viewer.terrainProvider,
    tempArray
  ); // 计算取样点的高度
  let minHeight = 8888;
  let maxHeight = 0;
  // 计算取样点的最小高度和最大高度
  for (let i = 0; i < updatedPositions.length; i++) {
    const height = updatedPositions[i].height;
    console.log(height);
    if (height < minHeight) {
      minHeight = height;
    }
    if (height > maxHeight) {
      maxHeight = height;
    }
  }
  waterHeight = Math.ceil(minHeight);
  minWaterHeight = Math.ceil(minHeight);
  maxWaterHeight = Math.ceil(maxHeight);
  // 禁用绘制按钮
  isDraw = !isDraw;
  return {
    minHeight,
    maxHeight,
  };
};

/**
 * @author:
 * @Date: 2024-09-06 16:46:47
 * @note: 注意事项
 * @description: 创建点
 * @param {*} worldPosition
 */
function createPoint(worldPosition) {
  const point = window.viewer.entities.add({
    name: "myId",
    position: worldPosition,
    point: {
      color: Cesium.Color.SKYBLUE,
      pixelSize: 5,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    },
  });
  return point;
}

/**
 * @author:
 * @Date: 2024-09-06 16:46:47
 * @note: 注意事项
 * @description: 绘制多边形
 * @param {*} positionData
 * @param {*} mat
 */
function drawShape(positionData, mat) {
  let shape = window.viewer.entities.add({
    polygon: {
      hierarchy: positionData,
      material: mat,
      outline: true,
      outlineColor: Cesium.Color.SKYBLUE,
      outlineWidth: 4,
    },
  });
  return shape;
}

/**
 * @author:
 * @Date: 2024-09-06 16:46:11
 * @note: 注意事项
 * @description: 绘制线
 * @param {*} positions
 */
function drawPolyline(positions) {
  if (positions.length < 1) return;

  let startP = positions[0];
  let endP = positions[positions.length - 1];
  if (startP.x != endP.x && startP.y != endP.y && startP.z != endP.z)
    positions.push(positions[0]);

  return (data.polylinedata = window.viewer.entities.add({
    name: "polyline",
    id: "myId",
    polyline: {
      positions: positions,
      width: 2.0,
      material: Cesium.Color.SKYBLUE,
      clampToGround: true,
    },
  }));
}

/**
 * @author:
 * @Date: 2024-09-06 16:45:05
 * @note: 注意事项
 * @description: 淹没分析
 */
var induationAnalysis = async () => {
  await getAreaHeight(activeShapePoints);

  // if (Number(warningWaterHeight) < Number(minWaterHeight) || Number(warningWaterHeight) > Number(maxWaterHeight)) {
  // 	$message({
  // 		message: '预警高度必须在最小高度和最小高度之间',
  // 		type: 'warning'
  // 	});
  // 	return
  // }
  let newData = [];
  let positionsArr = [];
  for (let i = 0; i < activeShapePoints.length; i++) {
    if (i < activeShapePoints.length - 1) {
      let cartographic = Cesium.Cartographic.fromCartesian(
        activeShapePoints[i]
      );
      newData.push(
        parseFloat(Cesium.Math.toDegrees(cartographic.longitude).toFixed(6)),
        parseFloat(Cesium.Math.toDegrees(cartographic.latitude).toFixed(6)),
        0
      );
      if (i == 0) {
        positionsArr.push(new Cesium.Cartesian2(0, 1));
      } else {
        if (i % 3 == 1) {
          positionsArr.push(new Cesium.Cartesian2(0, 0));
        } else if (i % 3 == 2) {
          positionsArr.push(new Cesium.Cartesian2(1, 0));
        } else if (i % 3 == 0) {
          positionsArr.push(new Cesium.Cartesian2(1, 1));
        }
      }
    }
  }
  console.log(positionsArr);
  let textureCoordinates = {
    positions: positionsArr,
  };
  console.log(newData);
  let aper = new Cesium.MaterialAppearance({
    material: new Cesium.Material({
      fabric: {
        uniforms: {
          iTime: 0,
          SEA_SPEED: 0.7, //流速
          SEA_DIRECTION: Cesium.Cartesian2.normalize(
            // new Cesium.Cartesian2(0, 1),
            // new Cesium.Cartesian2(0, 0),
            // new Cesium.Cartesian2(1, 0),
            // new Cesium.Cartesian2(1, 1)
            new Cesium.Cartesian2(1.0, 0.0),
            new Cesium.Cartesian2()
          ), //流向
          EL: 1.5, //深度
        },
        source: `
					const int NUM_STEPS = 8;
				  const float PI     = 3.141592;
				  const float EPSILON  = 1e-3;
				  //#define EPSILON_NRM (0.1 / iResolution.x)
				  #define EPSILON_NRM (0.1 / 200.0)
			
				  // sea  海洋参数
				  const int ITER_GEOMETRY = 3;    //定义几何迭代次数。在计算几何着色器中，这决定了波浪细节的精细程度。更高的值会生成更复杂的几何形状，但也会增加计算成本
				  const int ITER_FRAGMENT = 25;   //定义片段迭代次数。这控制了片段着色器中计算波浪细节的复杂度。同样，更高的值会带来更精细的效果，但也意味着更多的计算
				  const float SEA_HEIGHT = 0.19;   //海浪的高度
				  const float SEA_CHOPPY = 0.015;    //海面的“粗糙度”或波浪的强度
				 // const float SEA_SPEED = 0.8;      //流速
				  const float SEA_FREQ = 3.56;    //定义海浪的频率。这决定了波浪在单位距离内出现的次数，影响着海面波动的密集程度。
				  // const vec3 SEA_BASE = vec3(0.1,0.19,0.22);    //定义海水的基础颜色。这个向量包含了红、绿、蓝三个通道的颜色值，用于渲染水体的基本色调
				  const vec3 SEA_BASE = vec3(0.0 / 255.0, 70.0 / 255.0, 70.0 / 255.0);    //定义海水的基础颜色。这个向量包含了红、绿、蓝三个通道的颜色值，用于渲染水体的基本色调
				  // const vec3 SEA_WATER_COLOR = vec3(0.8,0.9,0.5);     //定义海水的颜色。不同于基础颜色，这个变量可能在着色器中用于调整水体在不同光照条件下的颜色表现，例如反射天空的颜色。
				   const vec3 SEA_WATER_COLOR = vec3(59.0 / 255.0, 64.0 / 255.0, 49.0 / 255.0);    //定义海水的基础颜色。这个向量包含了红、绿、蓝三个通道的颜色值，用于渲染水体的基本色调
				  //#define SEA_TIME (1.0 + iTime * SEA_SPEED)
			
				  const mat2 octave_m = mat2(1.6,1.2,-1.2,1.6);
			
				  // math 数学函数  // 从欧拉角转换为旋转矩阵
				  mat3 fromEuler(vec3 ang) {
					vec2 a1 = vec2(sin(ang.x),cos(ang.x));
					vec2 a2 = vec2(sin(ang.y),cos(ang.y));
					vec2 a3 = vec2(sin(ang.z),cos(ang.z));
					mat3 m;
					m[0] = vec3(a1.y*a3.y+a1.x*a2.x*a3.x,a1.y*a2.x*a3.x+a3.y*a1.x,-a2.y*a3.x);
					m[1] = vec3(-a2.y*a1.x,a1.y*a2.y,a2.x);
					m[2] = vec3(a3.y*a1.x*a2.x+a1.y*a3.x,a1.x*a3.x-a1.y*a3.y*a2.x,a2.y*a3.y);
					return m;
				  }
				  // 哈希函数
				  float hash( vec2 p ) {
					float h = dot(p,vec2(127.1,311.7));
					return fract(sin(h)*43758.5453123);
				  }
				  // 噪声函数
				  float noise( in vec2 p ) {
					vec2 i = floor( p );
					vec2 f = fract( p );
					vec2 u = f*f*(3.0-2.0*f);
					return -1.0+2.0*mix( mix( hash( i + vec2(0.0,0.0) ),
							 hash( i + vec2(1.0,0.0) ), u.x),
						  mix( hash( i + vec2(0.0,1.0) ),
							 hash( i + vec2(1.0,1.0) ), u.x), u.y);
				  }
			
				  // 光照函数
				  // 扩散反射
				  float diffuse(vec3 n,vec3 l,float p) {
					return pow(dot(n,l) * 0.4 + 0.6,p);
				  }
				  // 镜面反射
				  float specular(vec3 n,vec3 l,vec3 e,float s) {
					float nrm = (s + 8.0) / (PI * 8.0);
					return pow(max(dot(reflect(e,n),l),0.0),s) * nrm;
				  }
			
				  // sky // 天空颜色函数
				  vec3 getSkyColor(vec3 e) {
					e.y = max(e.y,0.0);
					return vec3(pow(1.0-e.y,2.0), 1.0-e.y, 0.6+(1.0-e.y)*0.4);
				  }
			
				  // 海洋相关函数
				  // 单一频段海洋波动
				  float sea_octave(vec2 uv, float choppy) {
					uv += noise(uv);
					vec2 wv = 1.0-abs(sin(uv));
					vec2 swv = abs(cos(uv));
					wv = mix(wv,swv,wv);
					return pow(1.0-pow(wv.x * wv.y,0.65),choppy);
				  }
			// 地形映射
				  float map(vec3 p) {
					float freq = SEA_FREQ;
					float amp = SEA_HEIGHT;
					float choppy = SEA_CHOPPY;
					vec2 uv = p.xz;
					uv.x *= 0.75;
					float d, h = 0.0;
					// float SEA_TIME = 1.0 + iTime * SEA_SPEED;
					//todu 新加的
					float SEA_TIME = 1.0 + dot(SEA_DIRECTION, vec2(iTime * SEA_SPEED, 0.0));
			
					for(int i = 0; i < ITER_GEOMETRY; i++) {
					  d = sea_octave((uv+SEA_TIME)*freq,choppy);
					  d += sea_octave((uv-SEA_TIME)*freq,choppy);
					  // h += d * amp;
					  //todu 新加的
					   h += d * amp * EL;
					  uv *= octave_m; freq *= 1.9; amp *= 0.22;
					  choppy = mix(choppy,1.0,0.2);
					}
					return p.y - h;
				  }
			// 详细地形映射
				  float map_detailed(vec3 p) {
					float freq = SEA_FREQ;
					float amp = SEA_HEIGHT;
					float choppy = SEA_CHOPPY;
					vec2 uv = p.xz; uv.x *= 0.75;
			
					 // float SEA_TIME = 1.0 + iTime * SEA_SPEED;
					 float SEA_TIME = 1.0 + dot(SEA_DIRECTION, vec2(iTime * SEA_SPEED, 0.0));
					float d, h = 0.0;
					for(int i = 0; i < ITER_FRAGMENT; i++) {
					  d = sea_octave((uv+SEA_TIME)*freq,choppy);
					  d += sea_octave((uv-SEA_TIME)*freq,choppy);
					  // h += d * amp;
						h += d * amp * EL;
					  uv *= octave_m; freq *= 1.9; amp *= 0.22;
					  choppy = mix(choppy,1.0,0.2);
					}
					return p.y - h;
				  }
			// 获取海洋颜色
				  vec3 getSeaColor(vec3 p, vec3 n, vec3 l, vec3 eye, vec3 dist) {
					float fresnel = clamp(1.0 - dot(n,-eye), 0.0, 1.0);
					fresnel = pow(fresnel,3.0) * 0.65;
			
					vec3 reflected = getSkyColor(reflect(eye,n));
					vec3 refracted = SEA_BASE + diffuse(n,l,80.0) * SEA_WATER_COLOR * 0.12;
			
					vec3 color = mix(refracted,reflected,fresnel);
			
					float atten = max(1.0 - dot(dist,dist) * 0.001, 0.0);
					color += SEA_WATER_COLOR * (p.y - SEA_HEIGHT) * 0.18 * atten;
			
					color += vec3(specular(n,l,eye,60.0));
			
					return color;
				  }
			
				  // tracing// 光线追踪函数
				   // 获取法线
				  vec3 getNormal(vec3 p, float eps) {
					vec3 n;
					n.y = map_detailed(p);
					n.x = map_detailed(vec3(p.x+eps,p.y,p.z)) - n.y;
					n.z = map_detailed(vec3(p.x,p.y,p.z+eps)) - n.y;
					n.y = eps;
					return normalize(n);
				  }
			// 高度图追踪
				  float heightMapTracing(vec3 ori, vec3 dir, out vec3 p) {
					float tm = 0.0;
					float tx = 1000.0;
					float hx = map(ori + dir * tx);
					if(hx > 0.0) return tx;
					float hm = map(ori + dir * tm);
					float tmid = 0.0;
					for(int i = 0; i < NUM_STEPS; i++) {
					  tmid = mix(tm,tx, hm/(hm-hx));
					  p = ori + dir * tmid;
					  float hmid = map(p);
					  if(hmid < 0.0) {
						tx = tmid;
						hx = hmid;
					  } else {
						tm = tmid;
						hm = hmid;
					  }
					}
					return tmid;
				  }
						// 主要材质函数
					   vec4 czm_getMaterial(vec2 vUv)
					   {
						vec2 uv = vUv;
						//todo 新加
						//   vec2 uv = vUv + iTime * SEA_SPEED * SEA_DIRECTION.xy;
			
						 float time = iTime * 0.3;
						 float el = EL;
						 // 使用SEA_DIRECTION和SEA_SPEED来控制河流流动
						 float SEA_TIME = 1.0 + dot(SEA_DIRECTION, vec2(iTime * SEA_SPEED, 0.0));
						// uv = vUv * 2.0 - 1.0;
						// float time = iTime * 0.3 + 0.0*0.01;
			
						// ray
						vec3 ang = vec3(0, 1.2, 0.0);
						  vec3 ori = vec3(0.0,3.5,0);
						vec3 dir = normalize(vec3(uv.xy,-2.0)); dir.z += length(uv) * 0.15;
						dir = normalize(dir) * fromEuler(ang);
			
						// tracing
						vec3 p;
						heightMapTracing(ori,dir,p);
						vec3 dist = p - ori;
						vec3 n = getNormal(p, dot(dist,dist) * EPSILON_NRM);
						vec3 light = normalize(vec3(0.0,1.0,0.8));
						// color
						vec3 color = mix(
						  getSkyColor(dir),
						  getSeaColor(p,n,light,dir,dist),
						  pow(smoothstep(0.0,-0.05,dir.y),0.3)
						  );
						  //设置透明度
						   float alpha = 0.5;
						   return vec4( pow(color,vec3(0.75)),alpha);
					   }
					`,
      },
    }),
    translucent: true,
    vertexShaderSource: `
					in vec3 position3DHigh;
					in vec3 position3DLow;
					in float batchId;
					in vec2 st;
					in vec3 normal;
					out vec2 v_st;
					out vec3 v_positionEC;
					out vec3 v_normalEC;
			
					void main() {
						v_st = st;
			
						vec4 p = czm_computePosition();
			
						v_positionEC = (czm_modelViewRelativeToEye * p).xyz;      // position in eye coordinates
						v_normalEC = czm_normal * normal;                         // normal in eye coordinates
			
						gl_Position = czm_modelViewProjectionRelativeToEye * p;
					}
								`,
    fragmentShaderSource: `
				  in vec2 v_st;
				  in vec3 v_positionEC;
				  in vec3 v_normalEC;
				  void main()  {
					vec3 positionToEyeEC = -v_positionEC;
					vec3 normalEC = normalize(v_normalEC);
					czm_materialInput materialInput;
					materialInput.normalEC = normalEC;
					materialInput.positionToEyeEC = positionToEyeEC;
					materialInput.st = v_st;
					vec4 color = czm_getMaterial(v_st);
					out_FragColor = color;
				  }
							`,
  });

  let primitive = new WaterPrimitive({
    aper: aper, //着色器
    positions: newData, //范围
    height: Number(minWaterHeight), //开始高度
    textureCoordinates: textureCoordinates, //自定义UV值
    speedVal: 0.05, //速度
    extrudedHeight: Number(minWaterHeight),
    targetHeight: Number(maxWaterHeight), //最大高度
    grow: true, //是否启用动态
    upGrow: true, //true 涨水  false 降水
  });

  let primitArr = viewer.scene.primitives.add(primitive);
  tempEntities.push(primitArr);
  function renderLoop(timestamp) {
    aper.material.uniforms.iTime = timestamp / 1000;
    requestAnimationFrame(renderLoop);
  }
  renderLoop();
};
/**
 * @author:
 * @Date: 2024-09-06 16:44:42
 * @note: 注意事项
 * @description: 清除当前页面所有数据
 */
function clearAllEntities() {
  yanmoshow.value = true;
  buttonshow.value = true;
  viewer.entities.removeById("myId");
  viewer.entities.removeAll();
  // viewer.entities.values.forEach((item, index) => {
  //   // 检查每个entity是否有name属性，并且该属性是否等于nameToRemove
  //   if (item.name == "myId") {
  //     // 如果满足条件，则删除该entity
  //     console.log(item);

  //     viewer.entities.remove(item);
  //   }
  // });
  // viewer.entities.removeByName("myId");
  viewer.camera.setView({
    destination: {
      x: -2850554.9246458095,
      y: 4656672.153306185,
      z: 3287574.727124352,
    },
    orientation: {
      heading: Cesium.Math.toRadians(48.72529042457395),
      pitch: Cesium.Math.toRadians(-10.899276751527792),
      roll: Cesium.Math.toRadians(0.0014027234956804583),
    },
  });
  // positions = [];
  const length = tempEntities.length;
  for (let f = 0; f < length; f++) {
    window.viewer.scene.primitives.remove(tempEntities[f]);
  }
  tempEntities = [];
  activeShapePoints = [];
  // warningWaterHeight = 0;
  isDraw = !isDraw;
  floatingPoint = undefined;
  activeShape = undefined;
  if (handler) {
    handler.destroy(); // 关闭事件句柄
    handler = undefined;
  }
}
const xiasnow = (value) => {
  if (value == "雪") {
    router.push("/particle/snow");
  } else if (value == "雨") {
    router.push("/particle/rain");
  } else if (value == "雾") {
    router.push("/particle/fog");
  } else if (value == "测量") {
    router.push("/geometry/measure");
    viewer.scene.globe.depthTestAgainstTerrain = false;
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        121.24728216278015,
        31.33460178267612,
        16300.423054364861
      ), // 纬度、经度和高度
      orientation: {
        heading: 0.7472338778188403,
        pitch: -1.5706868777202265,
        roll: 0,
      },
    });
  } else if (value == "绘制") {
    router.push("/geometry/draw");
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        121.24728216278015,
        31.33460178267612,
        16300.423054364861
      ), // 纬度、经度和高度
      orientation: {
        heading: 0.7472338778188403,
        pitch: -1.5706868777202265,
        roll: 0,
      },
    });
    // viewer.scene.globe.depthTestAgainstTerrain = false;
  } else if (value == "返回") {
    router.push("/");
    viewer.camera.setView({
      destination: {
        x: -2850554.9246458095,
        y: 4656672.153306185,
        z: 3287574.727124352,
      },
      orientation: {
        heading: Cesium.Math.toRadians(48.72529042457395),
        pitch: Cesium.Math.toRadians(-10.899276751527792),
        roll: Cesium.Math.toRadians(0.0014027234956804583),
      },
    });
    // main();
    // initViewer();
    // // initScene();
    // initEvent();
    // initGUI();
    // viewer.scene.globe.depthTestAgainstTerrain = false;
  }
  // router.push()
};
</script>


<style lang="scss" scoped>
html,
body,
#sceneContainer {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  // margin: 0;
  // padding: 0;
  overflow: hidden;
  background: #000;
}

#uiContainer {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  // margin: 0;
  // padding: 0;
  overflow: hidden;
}

#uiContainer {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  // margin: 0;
  // padding: 0;
  overflow: hidden;
}

#topUI {
  position: absolute;
  width: 100%;
  height: 10%;
  margin: 0;
  padding: 0;
  left: 0;
  top: 0;
  background-image: url("./Static/images/top.png");
  background-repeat: round;
  pointer-events: none;
}

#leftUI {
  position: absolute;
  width: 20%;
  height: 90%;
  margin: 0;
  padding: 0;
  left: 0;
  top: 5%;
  background-image: url("./Static/images/left.png");
  background-repeat: round;
  pointer-events: none;
}

#roghtUI {
  position: absolute;
  width: 20%;
  height: 90%;
  margin: 0;
  padding: 0;
  right: 0;
  top: 5%;
  background-image: url("./Static/images/right.png");
  background-repeat: round;
  pointer-events: none;
}

.loadingIndicator {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -33px;
  margin-left: -33px;
  width: 66px;
  height: 66px;
  z-index: 99;
  background-position: center;
  background-repeat: no-repeat;
  background-image: url("./Static/images/ajax-loader.gif");
}

.loadingIndicator2 {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background: #000;
}

.bvideo {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 13px;
  color: #fff;
  z-index: 9999;
}
.view {
  position: absolute;
  top: 10px;
  left: 110px;
  font-size: 13px;
  color: #fff;
  z-index: 9999;
}

.tankuang {
  width: 252px;
  height: 165px;
  background: url("@/assets/组.png") no-repeat;
  background-size: cover;
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%);
  color: white;
  padding: 0px 20px;
  box-sizing: border-box;
  .height {
    margin-top: 40px;
  }
  .height2 {
    margin-top: 2ex;
  }
  .close {
    position: absolute;
    top: 5px;
    left: 230px;
    width: 15px;
    height: 15px;
    cursor: pointer;
    // border: 1px solid red;
  }
}
</style>
